import log
import blue
import sys
import mathUtil
import util
import uicls
import re
from functools import wraps

def CropImage():
    ends = True
    import os
    import blue
    import trinity
    from util import ResFile
    sourceRoot = 'C:/Documents and Settings/Fridrik/Desktop/Incarna/bmp126'
    textures = os.listdir(sourceRoot)
    groups = {}
    lastGroupID = None
    for each in textures:
        if not each.endswith('.bmp'):
            continue
        cl = each.lstrip('_').lstrip('0').rstrip('.bmp')
        spl = cl.split('_')
        groupID = spl[0]
        if (spl[0] not in groups):
            groups[groupID] = []
        groups[groupID].append((int(spl[-1]), each))
        lastGroupID = groupID

    textureSize = 128
    srcCol = trinity.TriColor()
    for (groupID, subs,) in groups.iteritems():
        print 'colorAmount',
        print groupID,
        print [ bitNo for (bitNo, bitTexture,) in subs ]
        continue
        for (bitNo, bitTexture,) in subs:
            iconSurface = trinity.device.CreateOffscreenPlainSurface(textureSize, textureSize, trinity.TRIFMT_A8R8G8B8, trinity.TRIPOOL_SYSTEMMEM)
            iconSurface.LoadSurfaceFromFile(('C:\\Documents and Settings/Fridrik/Desktop/Incarna/bmps128Ends/' + bitTexture))
            iconSurface.LockBuffer()
            leftX = textureSize
            rightX = 0
            topY = textureSize
            bottomY = 0
            for x in xrange(textureSize):
                for y in xrange(textureSize):
                    srcCol.FromInt(iconSurface.GetPixel(x, y))
                    alpha = srcCol.a
                    if alpha:
                        leftX = min(x, leftX)
                        rightX = max(x, rightX)
                        topY = min(y, topY)
                        bottomY = max(y, bottomY)


            iconSurface.FlushBuffer()
            margin = 3
            leftX = max(0, (leftX - margin))
            rightX = min(textureSize, (rightX + margin))
            topY = max(0, (topY - margin))
            bottomY = min(textureSize, (bottomY + margin))
            rr = trinity.TriRect(leftX, topY, rightX, bottomY)
            iconID = ('%s_%sEnd__%s_%s_%s_%s.dds' % (groupID,
             bitNo,
             leftX,
             topY,
             rightX,
             bottomY))
            iconSurface.SaveSurfaceToFile(('C:/Documents and Settings/Fridrik/Desktop/Incarna/bmps128Ends/' + iconID), trinity.TRIIFF_DDS, rr)
            print 'Saving',
            print iconID

        blue.pyos.synchro.Yield()

    print 'Cropping Done'



def Merge(fromItem, destParent, register = False):
    for each in fromItem.children:
        item = each.CopyTo()
        destParent.children.append(item)
        if (register and getattr(destParent, 'sr', None)):
            destParent.sr.Set(item.name, item)




def DrawUnderline(self, buf, ulData):
    (xStart, xEnd, y, pitch, asc, des, (face, fontsize, color, flags,),) = ulData
    xStart = max(0, xStart)
    ulfgi = self.cmc.LookupFB(face, ord('_'), uicore.font.GetFallbackFonts())
    self.imageType.width = self.imageType.height = self.scaler.width = self.scaler.height = fontsize
    self.imageType.flags = flags
    self.GetMetrics(ulfgi[0])
    sbit = self.sbc.Lookup(self.imageType, ulfgi[1])
    widthScale = (float((xEnd - xStart)) / sbit.width)
    sbit.ToBuffer(buf.data, buf.width, buf.height, pitch, (xStart - (sbit.left * widthScale)), y, color, widthScale, tweak=True)



def GetBuffersize(size):
    if (size <= 8):
        return 8
    else:
        if (size <= 16):
            return 16
        if (size <= 32):
            return 32
        if (size <= 64):
            return 64
        if (size <= 128):
            return 128
        if (size <= 256):
            return 256
        if (size <= 512):
            return 512
        if (size <= 1024):
            return 1024
        if (size <= 2048):
            return 2048
        return 128



def StringColorToHex(color):
    colors = {'Black': '0xff000000',
     'Green': '0xff008000',
     'Silver': '0xffC0C0C0',
     'Lime': '0xff00FF00',
     'Gray': '0xff808080',
     'Grey': '0xff808080',
     'Olive': '0xff808000',
     'White': '0xffFFFFFF',
     'Yellow': '0xffFFFF00',
     'Maroon': '0xff800000',
     'Navy': '0xff000080',
     'Red': '0xffFF0000',
     'Blue': '0xff0000FF',
     'Purple': '0xff800080',
     'Teal': '0xff008080',
     'Fuchsia': '0xffFF00FF',
     'Aqua': '0xff00FFFF',
     'Orange': '0xffFF8000',
     'Transparent': '0x00000000',
     'Lightred': '0xffcc3333',
     'Lightblue': '0xff7777ff',
     'Lightgreen': '0xff80ff80'}
    return colors.get(color.capitalize(), None)



def Sort(lst):
    lst.sort(lambda x, y: cmp(str(x).upper(), str(y).upper()))
    return lst



def SortListOfTuples(lst, reverse = 0):
    lst.sort(reverse=reverse)
    return [ item[1] for item in lst ]



def SortByAttribute(lst, attrname = 'name', idx = None, reverse = 0):
    newlst = []
    for item in lst:
        if (idx is None):
            newlst.append((getattr(item, attrname, None), item))
        else:
            newlst.append((getattr(item[idx], attrname, None), item))

    ret = SortListOfTuples(newlst, reverse)
    return ret



def SmartCompare(x, y, sortOrder):
    for (column, direction,) in sortOrder:
        if (direction == 1):
            if (x[0][column] > y[0][column]):
                return 1
            if (x[0][column] < y[0][column]):
                return -1
        elif (x[0][column] < y[0][column]):
            return 1
        if (x[0][column] > y[0][column]):
            return -1

    return 0



def Update(*args):
    if (uicore.triapp and uicore.triapp.uilib):
        uicore.triapp.uilib.RecalcWindows()



def FindChild(fromParent, *names):
    if uicore.newRendererEnabled:
        return fromParent.FindChild(*names)
    else:
        ret = fromParent
        for name in names:
            ret = uicore.uilib.FindWindow(name, ret)
            if not ret:
                return 

        if ((not ret) or (ret == fromParent)):
            return 
        return ret



def GetChild(parent, *names):
    if uicore.newRendererEnabled:
        return parent.GetChild(*names)
    else:
        ret = parent
        for name in names:
            ret = uicore.uilib.FindWindow(name, ret)
            if ret:
                continue
            raise RuntimeError('ChildNotFound', (parent.name, names))
            continue

        if ((not ret) or (ret == parent)):
            raise RuntimeError('ChildNotFound', (parent.name, names))
        return ret



def FindChildByClass(parent, classes = (), searchIn = [], withAttributes = []):
    children = []
    for each in searchIn:
        for w in parent.Find(each):
            if isinstance(w, classes):
                if withAttributes:
                    for attrTuple in withAttributes:
                        (attr, value,) = attrTuple
                        if (getattr(w, attr, None) == value):
                            children.append(w)

                else:
                    children.append(w)


    return children



def SetOrder(child, idx = 0):
    if uicore.newRendererEnabled:
        child.SetOrder(idx)
        return 
    if not child.parent:
        log.LogError('Trying to change children order on parentless child', child)
        return 
    uicore.uilib.SetWindowOrder(child, idx)



def GetIndex(item):
    if item.parent:
        return item.parent.children.index(item)
    else:
        return 0



def Flush(parent):
    if ((parent is None) or (getattr(parent, 'destroyed', 0) or (not hasattr(parent, 'children')))):
        return 
    if hasattr(parent, 'Flush'):
        parent.Flush()
        return 
    for children in parent.children[:]:
        if ((children is not None) and (not getattr(children, 'destroyed', 0))):
            children.Close()

    del parent.children[:]



def FlushList(lst):
    for each in lst[:]:
        if ((each is not None) and (not getattr(each, 'destroyed', 0))):
            each.Close()

    del lst[:]



def GetWindowAbove(item):
    if (item == uicore.desktop):
        return 
    import uicls
    if (uicore.registry.IsWindow(item) and (not getattr(item, 'isImplanted', False))):
        return item
    if (item.parent and (not item.parent.destroyed)):
        return GetWindowAbove(item.parent)



def GetBrowser(item):
    if (item == uicore.desktop):
        return 
    if getattr(item, 'IsBrowser', None):
        return item
    import uicls
    if isinstance(item, uicls.EditCore):
        return item
    if item.parent:
        return GetBrowser(item.parent)



def GetAttrs(obj, *names):
    for name in names:
        obj = getattr(obj, name, None)
        if (obj is None):
            return 

    return obj



def Transplant(wnd, newParent, idx = None):
    if ((wnd is None) or (wnd.destroyed or ((newParent is None) or newParent.destroyed))):
        return 
    if (idx in (-1, None)):
        idx = len(newParent.children)
    if uicore.newRendererEnabled:
        wnd.SetParent(newParent, idx)
    else:
        par = getattr(wnd, 'parent', None)
        if (par is not None):
            wnd.parent.children.remove(wnd)
        newParent.children.insert(idx, wnd)



def IsClickable(wnd):
    if ((not hasattr(wnd, 'state')) or (not hasattr(wnd, 'parent'))):
        return False
    else:
        import uiconst
        if (wnd.state not in (uiconst.UI_NORMAL, uiconst.UI_PICKCHILDREN)):
            return False
        dad = wnd.parent
        if (dad == uicore.desktop):
            return True
        return IsClickable(dad)



def IsUnder(child, ancestor_maybe, retfailed = False):
    dad = child.parent
    if not dad:
        if retfailed:
            return child
        else:
            return False
        if (dad == ancestor_maybe):
            return True
        return IsUnder(dad, ancestor_maybe, retfailed)



def IsVisible(item):
    if ((not hasattr(item, 'state')) or (not hasattr(item, 'parent'))):
        return 0
    else:
        import uiconst
        if (item.state == uiconst.UI_HIDDEN):
            return 0
        dad = item.parent
        if not dad:
            return 0
        if (dad.state == uiconst.UI_HIDDEN):
            return 0
        if (dad == uicore.desktop):
            return 1
        return IsVisible(dad)



def IsVisible_RectCheck(item, rect = None):
    (il, it, iw, ih,) = item.GetAbsolute()
    if (rect is None):
        import trinity
        rect = trinity.TriRect(il, it, (il + iw), (it + ih))
        if (item.parent is None):
            return False
        else:
            return IsVisible_RectCheck(item.parent, rect)
        rect.left = max(rect.left, il)
        rect.top = max(rect.top, it)
        rect.right = min(rect.right, (il + iw))
        rect.bottom = min(rect.bottom, (it + ih))
        if ((rect.left >= rect.right) or (rect.top >= rect.bottom)):
            return False
        if (item.parent is uicore.desktop):
            return True
        if (item.parent is None):
            return False
        return IsVisible_RectCheck(item.parent, rect)



def GetIconDataFromIconPath(iconPath):
    import uiutil
    (texturePath, textureNo, iconSize, iconNo,) = uiutil.ParseIconPath(iconPath)
    (rectLeft, rectTop,) = GetTextureTranslation(iconNo, iconSize)
    return (texturePath,
     rectLeft,
     rectTop,
     iconSize,
     iconSize)



def MapIcon(sprite, iconPath, ignoreSize = 0):
    import uiconst
    import uiutil
    import trinity
    if iconPath.startswith('res:'):
        if not sprite.texture:
            sprite.texture = trinity.TriTexture()
        blue.resMan.SetUrgentResourceLoads(True)
        sprite.texture.pixels = iconPath
        blue.resMan.SetUrgentResourceLoads(False)
        return 
    (texturePath, textureNo, iconSize, iconNo,) = uiutil.ParseIconPath(iconPath)
    if uicore.newRendererEnabled:
        if ('uicore_' in iconPath):
            resPath = (iconPath.replace('uicore_', 'res:/uicore/texture/icons/') + '.dds')
        elif ('ui_' in iconPath):
            resPath = (iconPath.replace('ui_', 'res:/ui/texture/icons/') + '.dds')
        else:
            resPath = iconPath
        sprite.texturePrimary = trinity.Tr2Sprite2dTexture()
        sprite.texturePrimary.resPath = resPath
        sprite.texturePrimary.srcWidth = iconSize
        sprite.texturePrimary.srcHeight = iconSize
    else:
        (srcLeft, srcTop,) = GetTextureTranslation(iconNo, iconSize)
        if not sprite.texture:
            sprite.texture = trinity.TriTexture()
        blue.resMan.SetUrgentResourceLoads(True)
        sprite.texture.pixels = texturePath
        sprite.rectWidth = sprite.rectHeight = iconSize
        (sprite.rectLeft, sprite.rectTop,) = (srcLeft, srcTop)
        blue.resMan.SetUrgentResourceLoads(False)
    if ((not ignoreSize) and (sprite.GetAlign() != uiconst.TOALL)):
        sprite.width = iconSize
        sprite.height = iconSize



def MapIconData(sprite, iconData, ignoreSize = 0):
    (path, left, top, width, height,) = iconData
    sprite.texture.pixels = path
    sprite.rectWidth = width
    sprite.rectHeight = height
    sprite.rectLeft = left
    sprite.rectTop = top
    import uiconst
    if ((not ignoreSize) and (sprite.align != uiconst.UI_ALCLIENT)):
        sprite.width = width
        sprite.height = height



def GetTextureTranslation(iconNum, size = 64):
    step = (256 / size)
    x = ((iconNum - 1) % step)
    y = ((iconNum - 1) / step)
    return (int((x * size)), int((y * size)))


textureExistanceCache = []

def ParseIconPath(path):
    try:
        (root, textureNo, iconSize, iconNo,) = path.split('_')
        iconSize = int(iconSize)
        iconNo = int(iconNo)
    except:
        log.LogError('ParseIconPath; Invalid path, should be "root_textureNo_iconSize_iconNo" ', path)
        import uiconst
        return uiconst.FALLBACKICON
    if ((not path.startswith('uicore')) and (boot.appname == 'EVE')):
        texturePath = ('res:/%s/texture/icons/icons%s.dds' % (root, textureNo.zfill(2)))
    else:
        texturePath = ('res:/%s/texture/icons/%s_%s.dds' % (root,
         textureNo.zfill(3),
         iconSize))
    if (texturePath not in textureExistanceCache):
        f = blue.ResFile()
        if not f.FileExists(texturePath):
            import uiconst
            return uiconst.FALLBACKICON
        textureExistanceCache.append(texturePath)
    return (texturePath,
     textureNo,
     iconSize,
     iconNo)



def ConvertDecimal(qty, fromChar, toChar, numDecimals = None):
    import types
    ret = qty
    if (type(ret) in [types.IntType,
     types.FloatType,
     types.LongType]):
        if (numDecimals is not None):
            ret = ('%.*f' % (numDecimals, qty))
        else:
            ret = repr(qty)
    ret = ret.replace(fromChar, toChar)
    return ret



def GetClipboardData():
    import blue
    try:
        return blue.win32.GetClipboardUnicode()
    except blue.error:
        return ''



def GetTrace(item, trace = '', div = '/'):
    trace = ((div + item.name) + trace)
    if (getattr(item, 'parent', None) is None):
        return trace
    else:
        return GetTrace(item.parent, trace, div)



def PrepareDrag_Standard(dragContainer, dragSource, *args):
    uicls.Frame(parent=dragContainer)
    return (0, 0)



def GetImageSize(resPath):
    import blue
    import trinity
    from util import ResFile
    dev = trinity.device
    surface = dev.CreateOffscreenPlainSurface(8, 8, trinity.TRIFMT_A8R8G8B8, trinity.TRIPOOL_SYSTEMMEM)
    data = surface.LoadSurfaceFromFile(ResFile(resPath))
    return (data['Width'], data['Height'])



def ParseHTMLColor(colorstr, asTuple = 0, error = 0):
    colors = {'Black': '0x000000',
     'Green': '0x008000',
     'Silver': '0xC0C0C0',
     'Lime': '0x00FF00',
     'Gray': '0x808080',
     'Grey': '0x808080',
     'Olive': '0x808000',
     'White': '0xFFFFFF',
     'Yellow': '0xFFFF00',
     'Maroon': '0x800000',
     'Navy': '0x000080',
     'Red': '0xFF0000',
     'Blue': '0x0000FF',
     'Purple': '0x800080',
     'Teal': '0x008080',
     'Fuchsia': '0xFF00FF',
     'Aqua': '0x00FFFF',
     'Transparent': '0x00000000'}
    try:
        colorstr = colors.get(colorstr.capitalize(), colorstr).lower()
    except:
        sys.exc_clear()
        return colorstr
    if colorstr.startswith('#'):
        colorstr = colorstr.replace('#', '0x')
    (r, g, b, a,) = (0.0, 255.0, 0.0, 255.0)
    if colorstr.startswith('0x'):
        try:
            if (len(colorstr) == 8):
                r = eval(('0x' + colorstr[2:4]))
                g = eval(('0x' + colorstr[4:6]))
                b = eval(('0x' + colorstr[6:8]))
            elif (len(colorstr) == 10):
                a = eval(('0x' + colorstr[2:4]))
                r = eval(('0x' + colorstr[4:6]))
                g = eval(('0x' + colorstr[6:8]))
                b = eval(('0x' + colorstr[8:10]))
            else:
                log.LogWarn(('Invalid color string, has to be in form of 0xffffff or 0xffffffff (with alpha). 0x can be replaced with # (%s)' % colorstr))
                if error:
                    return 
        except:
            log.LogWarn(('Invalid color string, has to be in form of 0xffffff or 0xffffffff (with alpha). 0x can be replaced with # (%s)' % colorstr))
            if error:
                return 
    else:
        log.LogError(((('Unknown color (' + colorstr) + '), I only know: ') + strx(', '.join(colors.keys()))))
        if error:
            return 
    col = ((r / 255.0),
     (g / 255.0),
     (b / 255.0),
     (a / 255.0))
    if asTuple:
        return col
    else:
        import trinity
        return trinity.TriColor(*col)



def GetFormWindow(caption = None, buttons = None, okFunc = None, windowClass = None):
    import uicls
    import uiconst
    windowClass = (windowClass or uicls.Window)
    wnd = windowClass(parent=uicore.layer.main, width=256, height=128)
    if (caption is not None):
        wnd.SetCaption(caption)
    wnd.confirmCheckControls = []
    wnd.SetButtons((buttons or uiconst.OKCANCEL), okFunc=ConfirmFormWindow)
    return wnd



def AddFormControl(wnd, control, key, retval = None, required = False, errorcheck = None):
    wnd.confirmCheckControls.append((control,
     key,
     retval,
     required,
     errorcheck))



def AddFormErrorCheck(wnd, errorCheck):
    wnd.errorCheck = errorCheck



def ConfirmFormWindow(sender, *args):
    import uiconst
    import uicls
    uicore.registry.SetFocus(uicore.desktop)
    if ((sender is None) and getattr(uicore.registry.GetFocus(), 'stopconfirm', 0)):
        return 
    wnd = GetWindowAbove(sender)
    result = {}
    for each in getattr(wnd, 'confirmCheckControls', []):
        (control, key, retval, required, check,) = each
        checkValue = control.GetValue()
        if (required and ((checkValue is None) or (checkValue == ''))):
            uicore.Message('MissingRequiredField', {'fieldname': key})
            return 
        if check:
            hint = check(checkValue)
            if (hint == 'silenterror'):
                return 
            if hint:
                uicore.Message('CustomInfo', {'info': hint})
                return 
        if (type(retval) == dict):
            result.update(retval)
            continue
        result[key] = checkValue

    if not result:
        return 
    formErrorCheck = getattr(wnd, 'errorCheck', None)
    if (formErrorCheck and formErrorCheck):
        hint = formErrorCheck(result)
        if (hint == 'silenterror'):
            return 
        if hint:
            uicore.Message('CustomInfo', {'info': hint})
            return 
    wnd.result = result
    if (uicore.registry.GetModalWindow() == wnd):
        wnd.SetModalResult(uiconst.ID_OK)
    else:
        if wnd.sr.queue:
            wnd.sr.queue.put(result)
        wnd.SetModalResult(uiconst.ID_OK)
        return result



def AskAmount(caption = None, question = None, setvalue = '', intRange = None, floatRange = None):
    import uiconst
    import uicls
    if (caption is None):
        caption = 'How much?'
    if (question is None):
        question = 'How much?'
    wnd = GetFormWindow(caption)
    if question:
        uicls.Label(parent=wnd.sr.content, text=question, align=uiconst.TOTOP, pos=(0, 0, 0, 0))
    edit = uicls.SinglelineEdit(parent=wnd.sr.content, ints=intRange, floats=floatRange, setvalue=setvalue)
    AddFormControl(wnd, edit, 'amount', retval=None, required=True, errorcheck=None)
    if (wnd.ShowModal() == uiconst.ID_OK):
        return wnd.result



def AskName(caption = None, label = None, setvalue = '', maxLength = None, passwordChar = None, validator = None):
    import uiconst
    import uicls
    if (caption is None):
        caption = mls.UI_SHARED_TYPEINNAME
    if (label is None):
        label = mls.UI_SHARED_TYPEINNAME
    wnd = GetFormWindow(caption)
    if label:
        uicls.Label(parent=wnd.sr.content, text=label, align=uiconst.TOTOP, pos=(0, 0, 0, 0))
    edit = uicls.SinglelineEdit(parent=wnd.sr.content, maxLength=maxLength, setvalue=setvalue)
    AddFormControl(wnd, edit, 'name', retval=None, required=True, errorcheck=(validator or NamePopupErrorCheck))
    if (wnd.ShowModal() == uiconst.ID_OK):
        return wnd.result



def AskChoice(caption = '', question = '', choices = [], modal = False):
    import uiconst
    import uicls
    wnd = GetFormWindow(caption)
    if question:
        label = uicls.Label(parent=wnd.sr.content, text=question, align=uiconst.TOTOP, pos=(0, 0, 0, 0))
        wnd.SetMinSize(((label.width + 20), wnd.GetMinHeight()))
    combo = uicls.Combo(parent=wnd.sr.content, options=choices, align=uiconst.TOTOP)
    AddFormControl(wnd, combo, 'choice', retval=None, required=True, errorcheck=None)
    if modal:
        if (wnd.ShowModal() == uiconst.ID_OK):
            return wnd.result
    elif (wnd.ShowDialog() == uiconst.ID_OK):
        return wnd.result



def NamePopupErrorCheck(name):
    if ((not len(name)) or (len(name) and (len(name.strip()) < 1))):
        return mls.UI_SHARED_PLEASETYPESOMETHING
    else:
        return ''



def __CopyWithAlpha(srcSurface, dstSurface, srcSize, dstSize):
    srcSurface.LockBuffer()
    dstSurface.LockBuffer()
    import trinity
    tmpCol = trinity.TriColor()
    bpCol = trinity.TriColor()
    srcCol = trinity.TriColor()
    dstCol = trinity.TriColor()
    factor = (srcSize / dstSize)
    factor2 = (factor * factor)
    for x in xrange(dstSize):
        for y in xrange(dstSize):
            r = g = b = a = 0.0
            for xi in xrange(factor):
                for yi in xrange(factor):
                    srcCol.FromInt(srcSurface.GetPixel(((factor * x) + xi), ((factor * y) + yi)))
                    r += srcCol.r
                    g += srcCol.g
                    b += srcCol.b
                    a += srcCol.a


            if a:
                a /= factor2
                r /= factor2
                g /= factor2
                b /= factor2
                r *= a
                g *= a
                b *= a
                dstCol.FromInt(dstSurface.GetPixel(x, y))
                dstCol.Scale((1.0 - a))
                dstCol.r = min(1.0, (r + dstCol.r))
                dstCol.g = min(1.0, (g + dstCol.g))
                dstCol.b = min(1.0, (b + dstCol.b))
                dstCol.a = min(1.0, (a + dstCol.a))
                dstSurface.SetPixel(x, y, dstCol.AsInt())


    srcSurface.FlushBuffer()
    dstSurface.FlushBuffer()



def RenderIconSheets(iconRoot = 'res:/UI/Texture/Icons', bgcolor = (0.5, 0.5, 0.5), putInto = 'CCPIcons'):
    import os
    import blue
    import trinity
    from util import ResFile
    mydocs = blue.win32.SHGetFolderPath(blue.win32.CSIDL_PERSONAL)
    destRoot = ((mydocs + '\\') + putInto)
    try:
        os.makedirs(destRoot)
    except OSError, e:
        pass
    fullIconRoot = iconRoot.replace('res:/', blue.os.respath)
    textures = os.listdir(fullIconRoot)
    rot = blue.os.CreateInstance('blue.Rot')
    dev = trinity.device
    iconSurface = dev.CreateOffscreenPlainSurface(256, 256, trinity.TRIFMT_A8R8G8B8, trinity.TRIPOOL_SYSTEMMEM)
    col = trinity.TriColor()
    col.SetRGB(*bgcolor)
    html = '<htm><body>'
    for textureName in textures:
        if not textureName.endswith('.dds'):
            continue
        namesplit = textureName[:-4].split('_')
        if (len(namesplit) < 1):
            continue
        try:
            sheetNo = int(namesplit[0])
            iconSize = int(namesplit[1])
        except:
            continue
        resPath = ((iconRoot + '/') + textureName)
        iconSurface.LoadSurfaceFromFile(ResFile(resPath))
        sur = dev.CreateRenderTarget(256, 256, trinity.TRIFMT_A8R8G8B8, 0, 0, 1)
        surrect = trinity.TriRect(0, 0, 256, 256)
        dev.ColorFill(sur, surrect, col)
        sur.FlushBuffer()
        __CopyWithAlpha(iconSurface, sur, 256, 256)
        savesur = dev.CreateOffscreenPlainSurface(256, 256, trinity.TRIFMT_A8R8G8B8, trinity.TRIPOOL_SYSTEMMEM)
        sur.CopySurfaceTo(savesur)
        left = 0
        top = 0
        html += '<table cellspacing=4>'
        for i in xrange(((256 / iconSize) ** 2)):
            i += 1
            rr = trinity.TriRect(left, top, (left + iconSize), (top + iconSize))
            iconID = ('ui_%s_%s_%s.jpg' % (sheetNo,
             iconSize,
             i))
            savesur.SaveSurfaceToFile(((destRoot + '/') + iconID), trinity.TRIIFF_JPG, rr)
            if (left == 0):
                html += ('<tr height=%s>' % iconSize)
            magicStr = ('ui_%s_%s_%s' % (sheetNo,
             iconSize,
             i))
            html += ('<td><img src=%s></td>' % iconID)
            html += ('<td><font size=1>%s<br>Col: %s<br>Row: %s<br>Size: %s<br>Magic: %s</td>' % (resPath,
             (left / iconSize),
             (top / iconSize),
             iconSize,
             magicStr))
            left += iconSize
            if (left >= 256):
                left = 0
                top += iconSize
                html += '</tr>'

        html += '</table><br><br>'

    html += '</body></htm>'
    htmlfilePath = (destRoot + '/index.htm')
    fout = file(htmlfilePath, 'wb')
    fout.write(html)
    fout.close()



def BreakupUICoreIcons(iconRoot = 'res:/UICore/Texture/Icons'):
    import os
    import blue
    import trinity
    from util import ResFile
    destRoot = (blue.os.respath + '\\UICore\\Texture\\Icons')
    try:
        os.makedirs(destRoot)
    except OSError, e:
        pass
    fullIconRoot = iconRoot.replace('res:/', blue.os.respath)
    textures = os.listdir(fullIconRoot)
    rot = blue.os.CreateInstance('blue.Rot')
    dev = trinity.device
    iconSurface = dev.CreateOffscreenPlainSurface(256, 256, trinity.TRIFMT_A8R8G8B8, trinity.TRIPOOL_SYSTEMMEM)
    iconNo = 1
    for textureName in textures:
        if ((not textureName.endswith('.dds')) and (not textureName.startswith('00'))):
            continue
        namesplit = textureName[:-4].split('_')
        if (len(namesplit) < 1):
            continue
        try:
            sheetNo = int(namesplit[0])
            iconSize = int(namesplit[1])
        except:
            continue
        resPath = ((iconRoot + '/') + textureName)
        iconSurface.LoadSurfaceFromFile(ResFile(resPath))
        savesur = dev.CreateOffscreenPlainSurface(256, 256, trinity.TRIFMT_A8R8G8B8, trinity.TRIPOOL_SYSTEMMEM)
        iconSurface.CopySurfaceTo(savesur)
        left = 0
        top = 0
        for i in xrange(((256 / iconSize) ** 2)):
            i += 1
            rr = trinity.TriRect(left, top, (left + iconSize), (top + iconSize))
            iconID = ('ICON_%s.dds' % str(iconNo).zfill(4))
            oldstyleID = ('%s_%s_%s' % (sheetNo,
             iconSize,
             i))
            savesur.SaveSurfaceToFile((((destRoot + '/') + oldstyleID) + '.dds'), trinity.TRIIFF_DDS, rr)
            left += iconSize
            if (left >= 256):
                left = 0
                top += iconSize
            iconNo += 1





def BreakupIcons(iconRoot = 'res:/UI/Texture/Icons'):
    import os
    import blue
    import trinity
    from util import ResFile
    destRoot = (blue.os.respath + '\\UI\\Texture\\Icons')
    try:
        os.makedirs(destRoot)
    except OSError, e:
        pass
    fullIconRoot = iconRoot.replace('res:/', blue.os.respath)
    textures = os.listdir(fullIconRoot)
    rot = blue.os.CreateInstance('blue.Rot')
    dev = trinity.device
    iconSurface = dev.CreateOffscreenPlainSurface(256, 256, trinity.TRIFMT_A8R8G8B8, trinity.TRIPOOL_SYSTEMMEM)
    iconNo = 1
    for textureName in textures:
        if not textureName.endswith('.dds'):
            continue
        if (textureName.find('.ZH') != -1):
            continue
        print 'Doing',
        print textureName
        namesplit = textureName[:-4].split('_')
        if (len(namesplit) < 1):
            continue
        try:
            sheetNo = int(namesplit[0])
            iconSize = int(namesplit[1])
        except:
            continue
        resPath = ((iconRoot + '/') + textureName)
        iconSurface.LoadSurfaceFromFile(ResFile(resPath))
        savesur = dev.CreateOffscreenPlainSurface(256, 256, trinity.TRIFMT_A8R8G8B8, trinity.TRIPOOL_SYSTEMMEM)
        iconSurface.CopySurfaceTo(savesur)
        left = 0
        top = 0
        for i in xrange(((256 / iconSize) ** 2)):
            i += 1
            rr = trinity.TriRect(left, top, (left + iconSize), (top + iconSize))
            iconID = ('ICON_%s.png' % str(iconNo).zfill(4))
            oldstyleID = ('%s_%s_%s' % (sheetNo,
             iconSize,
             i))
            savesur.SaveSurfaceToFile((((destRoot + '/') + oldstyleID) + '.dds'), trinity.TRIIFF_DDS, rr)
            left += iconSize
            if (left >= 256):
                left = 0
                top += iconSize
            iconNo += 1





def BreakupEveIcons(iconRoot = 'res:/UI/Texture/Icons'):
    import os
    import blue
    import trinity
    import uix
    from util import ResFile
    BreakupUICoreIcons()
    destRoot = (blue.os.respath + '\\UI\\Texture\\Icons')
    try:
        os.makedirs(destRoot)
    except OSError, e:
        pass
    fullIconRoot = iconRoot.replace('res:/', blue.os.respath)
    textures = os.listdir(fullIconRoot)
    rot = blue.os.CreateInstance('blue.Rot')
    dev = trinity.device
    iconSurface = dev.CreateOffscreenPlainSurface(256, 256, trinity.TRIFMT_A8R8G8B8, trinity.TRIPOOL_SYSTEMMEM)
    iconNo = 1
    for textureName in textures:
        if ((not textureName.endswith('.dds')) and (not textureName.startswith('icons'))):
            continue
        namesplit = textureName[:-4].split('_')
        if (len(namesplit) < 1):
            continue
        splits = textureName[5:-4].split('.')
        if (len(splits) > 1):
            isZH = True
        else:
            isZH = False
        iconSize = uix.GetIconSize(splits[0])
        sheetNo = int(splits[0])
        resPath = ((iconRoot + '/') + textureName)
        iconSurface.LoadSurfaceFromFile(ResFile(resPath))
        savesur = dev.CreateOffscreenPlainSurface(256, 256, trinity.TRIFMT_A8R8G8B8, trinity.TRIPOOL_SYSTEMMEM)
        iconSurface.CopySurfaceTo(savesur)
        left = 0
        top = 0
        for i in xrange(((256 / iconSize) ** 2)):
            i += 1
            rr = trinity.TriRect(left, top, (left + iconSize), (top + iconSize))
            oldstyleID = ('%s_%s_%s' % (sheetNo,
             iconSize,
             i))
            if isZH:
                oldstyleID += '.ZH'
            savesur.SaveSurfaceToFile((((destRoot + '/') + oldstyleID) + '.dds'), trinity.TRIIFF_DDS, rr)
            left += iconSize
            if (left >= 256):
                left = 0
                top += iconSize
            iconNo += 1





def FindWordBoundaries(text):
    import uiconst
    return [ token for token in uiconst.WORD_BOUNDARY_REGEX.split(text) if token ]



def ParanoidDecoMethod(fn, attrs):
    check = []
    if (attrs is None):
        check = ['sr']
    else:
        check.extend(attrs)

    @wraps(fn)
    def deco(self, *args, **kw):
        if (util.GetAttrs(self, *check) is None):
            return 
        else:
            if self.destroyed:
                return 
            return fn(self, *args, **kw)


    return deco



def NiceFilter(func, list):
    ret = []
    for x in list:
        if func(x):
            ret.append(x)
        blue.pyos.BeNice()

    return ret



def AutoExports(namespace, globals_):
    import types
    return dict([ (('%s.%s' % (namespace, name)), val) for (name, val,) in globals_.iteritems() if ((not name.startswith('_')) and (not isinstance(val, types.ModuleType))) ])


exports = AutoExports('uiutil', locals())

